package com.lifeng.mynetty.client;

import com.lifeng.mynetty.client.handler.TcpClientHandler;
import com.lifeng.mynetty.common.Client;
import com.lifeng.mynetty.constants.MyNettyContants;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * Created by lifeng
 * 2017/9/1 15:45
 */
public class TcpClient implements Client{
    private static Logger logger = LoggerFactory.getLogger(TcpClient.class);
    //字符编码
    private String ip;
    private int port = -1;
    private String charset = "utf-8";
    private Bootstrap bootstrap;
    public void start() throws Exception {
        if(ip == null || "".equals(ip)){
            logger.error("ip或主机配置有误,请重新配置");
            throw new Exception("ip或主机配置有误,请重新配置");
        }
        if(-1 == port){
            logger.error("端口:"+port+"配置有误");
            throw new Exception("端口:"+port+"配置有误");
        }
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(Charset.forName(charset)));
                pipeline.addLast("encoder", new StringEncoder(Charset.forName(charset)));
                pipeline.addLast("handler", new TcpClientHandler(charset));
            }
        });

    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }
    @Override
    public void send(byte[] msg) throws Exception {
        send(null,msg);
    }

    @Override
    public void send(String msgId, byte[] msg) throws Exception {
        Channel channel = bootstrap.connect(ip, port).sync().channel();
        ByteBuf buf = Unpooled.copiedBuffer(msg);
        //为了回填响应消息
        if(msgId != null && !"".equals(msgId)){
            channel.attr(AttributeKey.newInstance(MyNettyContants.MSG_KEY)).set(msgId);
        }
        channel.writeAndFlush(buf).sync();
    }
}
